﻿#include <QTcpSocket>
#include "ethernet.h"

Ethernet::Ethernet(QObject *parent)
    : Device{parent}
    , m_strIP("192.168.1.1")
    , m_nPort(1000)
    , tcpSubClient(new TCPSubClient(parent))
{

}

QString Ethernet::strIP() const
{
    return m_strIP;
}

void Ethernet::setStrIP(const QString &newStrIP)
{
    if (m_strIP == newStrIP)
        return;
    m_strIP = newStrIP;
    emit strIPChanged();
}

int Ethernet::nPort() const
{
    return m_nPort;
}

void Ethernet::setNPort(int newNPort)
{
    if (m_nPort == newNPort)
        return;
    m_nPort = newNPort;
    emit nPortChanged();
}

int Ethernet::initDevice() {
    return tcpSubClient->connectToServer(m_strIP,m_nPort);
}

void Ethernet::uninitDevice() {
    tcpSubClient->disconnect();
}

QString Ethernet::getClassName()
{
    return this->metaObject()->className();
}

void Ethernet::writeXML(QXmlStreamWriter &writer)
{
    // 写入当前操作的信息
    writer.writeStartElement("Ethernet");
    writer.writeAttribute(QStringLiteral("id"), m_strID);

    writer.writeTextElement("ip", m_strIP);
    writer.writeTextElement("port", QString::number(m_nPort));
    writer.writeEndElement(); // 结束当前操作的元素
}

void Ethernet::readFromXML(QXmlStreamReader &reader)
{
    QXmlStreamAttributes attributes = reader.attributes();
    if (attributes.hasAttribute("id")) {
        m_strID = attributes.value("id").toString();
    }

    QXmlStreamReader::TokenType token = reader.readNext();
    while (!(reader.tokenType() == QXmlStreamReader::EndElement
             && reader.name() == QStringLiteral("Ethernet"))) {
        if (reader.name() == QStringLiteral("ip")) {
            m_strIP = reader.readElementText();
        } else if (reader.name() == QStringLiteral("port")) {
            m_nPort = reader.readElementText().toInt();
        }

        reader.readNext();
    }
}

void Ethernet::writeData(const QVariant &data) {
    QByteArray bytes = data.toByteArray();
    tcpSubClient->sendRawMessage(bytes);
}
